class_name PlayerHurtBoxComponent
extends Area2D

## 用来控制玩家健康相关的功能

@export var player: Player
@export var player_state: PlayerState

signal on_die()
signal on_hurt()

var time = 0
func hurt(_hitbox, damage: float) -> void:
	on_hurt.emit()
	get_tree().call_group("control", "hit")
	Utils.show_hit_label_c(damage, self, Color.RED)
	Utils._freeze_frame(0.1)
	print("玩家收到伤害: %s" % [damage])
	player_state.state_send_event("to_hurt")
	var current_hp = Utils.get_player_stats_value("current_hp")
	# 检查是否有格挡buff
	if player.buff_manager.has_buff("格挡"):
		print("格挡成功！伤害被完全抵消")
		Utils.show_string_label_c("格挡！", self, Color.CYAN)
		# 移除格挡buff（一次性使用）
		player.buff_manager.remove_buff("格挡")
		return
	if current_hp - damage <= 0:
		if player.buff_manager.has_buff("闪亮之珠"):
			Utils.set_player_stats_value("current_hp", -current_hp + 0.01 )
			var current_mp = Utils.get_player_stats_value("current_mp")
			## 蓝条够就不死亡
			if current_mp >= damage - current_hp:
				Utils.set_player_stats_value("current_mp", -damage + current_hp)
			else:
				Utils.set_player_stats_value("current_mp", -current_mp)
				Utils.set_player_stats_value("current_hp", -0.01 )
				on_die.emit()
				player_state.state_send_event("to_die")
				print("玩家死亡")
		else:
			Utils.set_player_stats_value("current_hp", -current_hp)
			on_die.emit()
			player_state.state_send_event("to_die")
			print("玩家死亡")
		return

	Utils.set_player_stats_value("current_hp", -damage)


func _physics_process(delta: float) -> void:
	time += delta
	if time > 1:
		time = 0
		var health_regen = Utils.get_player_stats_value("health_regen")
		var current_hp = Utils.get_player_stats_value("current_hp")
		var max_hp = Utils.get_player_stats_value("max_hp") + Utils.get_player_stats_value("additional_hp")
		if health_regen + current_hp > max_hp:
			Utils.set_player_stats_value("current_hp", max_hp - current_hp)
		else:
			Utils.set_player_stats_value("current_hp", health_regen)
		var mp_regen = Utils.get_player_stats_value("mp_regen")
		var current_mp = Utils.get_player_stats_value("current_mp")
		var max_mp = Utils.get_player_stats_value("max_mp")
		if mp_regen + current_mp > max_mp:
			Utils.set_player_stats_value("current_mp", max_mp - current_mp)
		else:
			Utils.set_player_stats_value("current_mp", mp_regen)


func _on_area_entered(area: Area2D) -> void:
	if area.is_in_group("enemy"):
		on_hurt.emit(area, area.damage)
